#include <stdio.h>
#include "emqtt.h"
#include <reg51.h>

#define RCVBUFSIZE 1024
unsigned char packet_buffer[RCVBUFSIZE];
int keepalive = 30;
mqtt_broker_handle_t broker;


int init_socket(mqtt_broker_handle_t *broker, const char *hostname, short port)
{
    int flag = 1;
    keepalive = 3;
    //at??á?á??óhostname port ·t???÷
    //1?±?at??á?
    mqtt_set_alive(broker, keepalive);
    return 0;
}

int read_packet(int timeout)
{

    //μè′yéè??ê±????oó???óê?μ?μ?êy?Y×ü3¤?è·μ??
    //·μ??êy?Y×ü3¤?è
    //???óê?μ?μ?êy?Y·?è?packet_buffer￡?2￠·μ???óê?μ?μ?êy?Y3¤?è
    return 0;//packet_length;
}

int topmqtt(void)
{
    int packet_length;
    unsigned int msg_id, msg_id_rcv;

    //×?·?′?±íê???2ú?·μ??¨ò?±êê???
    mqtt_init(&broker, "avengalvon");
    //é?ê?2ù×÷????ê???êy?Y?′??μ??á11ì??ú2???????DD·t???÷á??ó
    init_socket(&broker, "123.56.29.115", 1883);
    //·￠?íá??ó???ó
    mqtt_connect(&broker);
    //μè′y?áè?á??ó???ó·μ??°ü
    packet_length = read_packet(1);
    //í¨1y?óê?μ?êy?Y°ü3¤?èà′?D??á??óê?·?3é1|
    if(packet_length < 0)
    {
        printf("Error(%d) on read packet!\n", packet_length);
        return -1;
    }

    if(MQTTParseMessageType(packet_buffer) != MQTT_MSG_CONNACK)
    {
        printf("CONNACK expected!\n");
        return -2;
    }

    if(packet_buffer[3] != 0x00)
    {
        printf("CONNACK failed!\n");
        return -2;
    }

    //á??ó3é1|oó ??DDêy?Y·￠2? ·￠2??÷ìa?a?°hello? ±
    mqtt_publish(&broker, "hello", "Example: QoS 0", 0);

    //?ù?Y????ê±???¨ê±·￠?ímqtt_ping();

    //?????÷ìa
    mqtt_subscribe(&broker, "public/test/topic", &msg_id);
    //????3é1|?é?¤
    if(packet_length < 0)
    {
        printf("Error(%d) on read packet!\n", packet_length);
        return -1;
    }

    if(MQTTParseMessageType(packet_buffer) != MQTT_MSG_SUBACK)
    {
        printf("SUBACK expected!\n");
        return -2;
    }

    msg_id_rcv = mqtt_parse_msg_id(packet_buffer);
    if(msg_id != msg_id_rcv)
    {
        printf("%d message id was expected, but %d message id was found!\n", msg_id, msg_id_rcv);
        return -3;
    }
    //μè′yêy?Y?óê?
    while(1)
    {
        // <<<<<
        packet_length = read_packet(0);
        if(packet_length == -1)
        {
            printf("Error(%d) on read packet!\n", packet_length);
            return -1;
        }
        else if(packet_length > 0)
        {
            printf("Packet Header: 0x%x...\n", packet_buffer[0]);
            if(MQTTParseMessageType(packet_buffer) == MQTT_MSG_PUBLISH)
            {
                unsigned char topic[255], msg[1000];
                unsigned int len;
                len = mqtt_parse_pub_topic(packet_buffer, topic);
                topic[len] = '\0'; // for printf
                len = mqtt_parse_publish_msg(packet_buffer, msg);
                msg[len] = '\0'; // for printf
                printf("%s %s\n", topic, msg);
            }
        }

    }
}
